package l1j.server.server.datatables;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.server.DatabaseFactory;
import l1j.server.server.templates.L1Decompose;
import l1j.server.server.utils.PerformanceTimer;
import l1j.server.server.utils.SQLUtil;

public class DecomposeTable {

	private static final Logger _log = Logger.getLogger(DecomposeTable.class.getName());

	private final HashMap<Integer , ArrayList<L1Decompose>>_map = new HashMap<Integer , ArrayList<L1Decompose>>();

	private static DecomposeTable _instance;
	
	public static DecomposeTable get(){
		if(_instance == null){
			_instance = new DecomposeTable();
		}
		return _instance;
	}
	
	public void load(){
		final PerformanceTimer timer = new PerformanceTimer();
		Connection con = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			con = DatabaseFactory.get().getConnection();
			pstm = con.prepareStatement("SELECT * FROM `z_opqlo_分解清單`");
			rs = pstm.executeQuery();
			int size =0;
			while(rs.next()){
				final int srcitemid = rs.getInt("srcItemId");
				final L1Decompose temp = new L1Decompose();
				if(	temp.setItemId(rs.getInt("itemId"))){
					temp.setChance(rs.getInt("Chance"));
					temp.setMinCount(rs.getInt("MinCount"));
					temp.setMaxCount(rs.getInt("MaxCount"));
					
					final ArrayList<L1Decompose> list;
					
					if(_map.containsKey(srcitemid)){
						list = _map.get(srcitemid);
					}else{
						list = new ArrayList<L1Decompose>();
						_map.put(srcitemid, list);
					}
					list.add(temp);
					size++;
				}else{
					_log.info("【警告】物品拆解資料異常，編號:"+srcitemid+" 找不到這個道具。");
				}
			}
			_log.info("載入物品分解資料數量: " + size + "(" + timer.get() + "ms)");			
		} catch (final SQLException e) {
			_log.log(Level.WARNING,e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(rs);
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}
	
	public ArrayList<L1Decompose>getList(final int itemid){
		if(_map.containsKey(itemid)){
			ArrayList<L1Decompose> list = new ArrayList<L1Decompose>();
			list.addAll(_map.get(itemid));
			return list;
		}
		return null;
	}
	
	public boolean hasTemp(final int itemid){
		return _map.containsKey(itemid);
	}
	
	
}
